<?php
/**
 * Created by PhpStorm.
 * User: huqi
 * Date: 2019-12-29
 * Time: 00:59
 */

namespace WebUtil\Matrix;


class Parser
{
    public $code;
    public $index;
    public $len;

    public static function instance($code, $index = 0){
        return (new static($code,$index));
    }

    public function __construct($code , $index = 0)
    {
        $this->code = $code;
        $this->index = $index ;
        $this->len = strlen($this->code);
    }

    public function isSpace($str){
        return preg_match("/^\s+$/",$str);
    }

    public function fetchWord(){
        $this->skipSpace();
        $idx = $this->index;
        while ($this->index < $this->len){
            if ($this->isSpace($this->char())){
                break;
            }
            $this->index++;
        }
        return $this->cut($this->index,$idx);
    }

    public function fetchUtil($str){
        $idx = $this->index;
        $offset = strlen($str);
        while ($this->index < $this->len) {
            if ($this->chars($offset) === $str){
                $this->index += $offset;
                break;
            }
            $this->index++;
        }
        return $this->cut($this->index,$idx);
    }

    public function skipSpace(){
        while ($this->index < $this->len && $this->isSpace($this->char())){
            $this->index++;
        }
    }

    public function char(){
        return $this->code[$this->index];
    }

    public function chars($offset , $start = -1){
        return substr($this->code, $start === -1 ? $this->index : $start ,$offset);
    }

    public function cut($end,$start = -1){
        return substr($this->code, $start === -1 ? $this->index : $start, $end-$start);
    }

    public function isEnd()
    {
        return $this->index >= $this->len - 1;
    }
}